package com.googlecode.gwtbb.client.only.widget.form;

import com.google.gwt.user.client.ui.*;
import com.google.gwt.widgetideas.client.GlassPanel;
import com.googlecode.gwtbb.client.only.GwtbbCmess;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since May 28, 2008
 */
public class FormDialog extends DialogBox implements CompleteProcessListener {
	private FormWidget formWidget;
	private FormSuccessPopupPanel successPopup = new FormSuccessPopupPanel();
	private GlassPanel glassPanel;

	private final ClickListener cancelButtonListener = new ClickListener() {
		public void onClick(Widget sender) {
			hide();
		}
	};

	public FormDialog() {
		setText(GwtbbCmess.instance().loading());
		VerticalPanel loadingForm = new VerticalPanel();
		setWidget(loadingForm);
		loadingForm.add(new Label(GwtbbCmess.instance().loadingForm()));
		ButtonBar buttonBar = new ButtonBar();
		loadingForm.add(buttonBar);
		Button cancelButton = new Button(GwtbbCmess.instance().cancel());
		buttonBar.add(cancelButton);
		cancelButton.addClickListener(cancelButtonListener);
	}

	public FormDialog(FormWidget formWidget) {
		setFormWidget(formWidget);
	}

	public FormWidget getFormWidget() {
		return formWidget;
	}

	@Override
	public void hide() {
		if (glassPanel != null) {
			RootPanel.get().remove(glassPanel);
		}
		super.hide();
	}

	public void onProcessCompletion(ProcessEvent processEvent) {
		hide();
	}

	public void setFormWidget(FormWidget formWidget) {
		if (this.formWidget != null) {
			this.formWidget.getCompleteProcessListenerCollection().removeCompleteProcessListener(this);
		}
		this.formWidget = formWidget;
		setWidget(formWidget);
		formWidget.getCancelButton().addClickListener(cancelButtonListener);
		formWidget.getCompleteProcessListenerCollection().addCompleteProcessListener(this);
		setText(formWidget.getProcessTitle());
		successPopup.setFormWidget(formWidget);
	}

	@Override
	public void show() {
		if (glassPanel == null) {
			glassPanel = new GlassPanel(false);
		}
		RootPanel.get().add(glassPanel, 0, 0);
		super.show();
	}
}
